package com.yishun.springboot.service;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import lombok.Setter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yinquan.util.DataUtil;
import com.yinquan.util.HttpGet;
import com.yinquan.util.StoreFileUtil;
import com.yinquan.util.YzwBusinessUtil;
import com.yishun.springboot.mapper.GwsAndYzwTeamDaoMapper;
import com.yishun.springboot.mapper.GwsCWRMapper;
import com.yishun.springboot.mapper.GwsCorYzwTeamMapper;
import com.yishun.springboot.mapper.GwsPersonMapper;
import com.yishun.springboot.mapper.GwsPushDataMapper;
import com.yishun.springboot.mapper.GwsWorkerlistMapper;
import com.yishun.springboot.mapper.IntelligentsiteCorrespondsMapper;
import com.yishun.springboot.mapper.ModuleDetailedCorrespondingProjectNoMapper;
import com.yishun.springboot.mapper.YzwProjectKeyAndCodeMapper;
import com.yishun.springboot.mapper.YzwSubContractorListMapper;
import com.yishun.springboot.mapper.YzwTeamMasterMapper;
import com.yishun.springboot.mapper.YzwWorkerListMapper;
import com.yishun.springboot.pojo.GwsAndYzwTeamDao;
import com.yishun.springboot.pojo.GwsAttendanceDTO;
import com.yishun.springboot.pojo.GwsCorYzwTeam;
import com.yishun.springboot.pojo.GwsDictListJobName;
import com.yishun.springboot.pojo.GwsPerson;
import com.yishun.springboot.pojo.GwsProjectAttendanceListNew;
import com.yishun.springboot.pojo.GwsPushData;
import com.yishun.springboot.pojo.GwsTeam;
import com.yishun.springboot.pojo.GwsTeamType;
import com.yishun.springboot.pojo.GwsWorkerlist;
import com.yishun.springboot.pojo.IntelligentsiteCorrespondsItemtable;
import com.yishun.springboot.pojo.ModuleDetailedCorrespondingProject;
import com.yishun.springboot.pojo.YzwProjectAttendanceListNew;
import com.yishun.springboot.pojo.YzwProjectKeyAndCode;
import com.yishun.springboot.pojo.YzwSubContractorList;
import com.yishun.springboot.pojo.YzwWorkerList;

import lombok.extern.slf4j.Slf4j;

/**
 * 业务层-上传工务署实名制各项数据
 *
 * @author XiaoHuang
 * @date 2021年5月11日上午9:23:00
 */

@Slf4j
@Service
@Component
public class GongWuSuUploadCWSService {

    // 是否详细记录
    static Boolean detailedRecordLong = false;

    // 工务署业务服务类
    @Autowired
    InnerFormalGWSCWRService innerFormalGWSCWRService;

    @Autowired
    ModuleDetailedCorrespondingProjectNoMapper moduleDetailedCorrespondingProjectNoMapper;

    @Autowired
    IntelligentsiteCorrespondsMapper intelligentsiteCorrespondsMapper;

    @Autowired
    YzwWorkerListMapper yzwWorkerListMapper;

    // 工务署服务mapper
    @Autowired
    GwsCWRMapper gwsCWRMapper;

    @Autowired
    GwsWorkerlistMapper gwsWorkerlistMapper;

    @Autowired
    YzwSubContractorListMapper yzwSubContractorListMapper;

    @Autowired
    RealNameSystemInterfaceService realNameSystemInterfaceService;

    @Autowired
    DirectlyConnectedYzwPersonService directlyConnectedYzwPersonService;

    @Autowired
    YzwProjectKeyAndCodeMapper yzwProjectKeyAndCodeMapper;

    @Autowired
    GwsPushDataMapper gwsPushDataMapper;

    @Autowired
    YzwTeamMasterMapper yzwTeamMasterMapper;

    @Autowired
    GwsCorYzwTeamMapper gwsCorYzwTeamMapper;

    @Autowired
    GwsPersonMapper gwsPersonMapper;

    @Resource
    GwsAndYzwTeamDaoMapper gwsAndYzwTeamDaoMapper;

    // 考勤接口用到

    // 已修改为正确的
    // public String api_key = "ab3d511304f44a10b3e194dca22f6c03";// √
    // public String api_secret = "f53441147bc24290b4131436c40d2e27";// √
    // public String client_serial = "f53441147bc24290b4131436c40d2e27";// √
    // public String api_version = "1.0";// √
    // public String Project_ID = "XM20190707";// 工程编码 //√

    // （工务署平台已经废除该接口）
    // public String uploadCompany(String gwsProjectCode,Integer
    // yzwProjectCode,String projectName){
    // GwsPushData gwsPushData =
    // gwsPushDataMapper.selectOneRecordByGwsProjectCode(gwsProjectCode);
    // if(gwsPushData == null)
    // return "结束（跳过）";
    // List<YzwSubContractorList> yzwSubList =
    // yzwSubContractorListMapper.findOneRecordByProjectCode(yzwProjectCode);
    // YzwSubContractorList yzwSubContractor = null;
    // JSONObject bodyjson = new JSONObject();
    // //数据组织-header（公用于每个请求）
    // String apiKey = gwsPushData.getApiKey();
    // String apiSecret = gwsPushData.getApiSecret();
    // String clientSerial = gwsPushData.getClientSerial();
    // String apiVersion = gwsPushData.getApiVersion();
    // String timestamp = DataUtil.currTime();
    // //一个参建单位，一个请求
    // for (int i = 0; i < yzwSubList.size(); i++) {
    // yzwSubContractor = yzwSubList.get(i);
    // //数据组织-body
    // bodyjson.put("Company_Name", yzwSubContractor.getSubContractorName());
    // bodyjson.put("Project_ID", gwsProjectCode);
    // bodyjson.put("SUID", yzwSubContractor.getSocialCreditNumber());
    // bodyjson.put("Legal_Person", "");
    // bodyjson.put("Type", "016");//单位类型
    // bodyjson.put("entry_time", timestamp);
    // }
    //
    // return innerFormalGWSCWRService.addCompany(bodyjson,
    // apiKey,apiSecret,clientSerial,apiVersion,timestamp);
    // }

    /**
     * 上传考勤
     *
     * @throws Exception
     */
    public String uploadPersonnelPassageData(Boolean directlyConnectedYzwPersonnelPassageData, String gwsProjectCode,
                                             Integer yzwProjectCode, String projectName) {
        log.info("工务署业务模块-开始上传考勤到工务署..");
        JSONObject paramjson = new JSONObject();

        log.info("工务署业务模块-上传考勤到工务署-项目对应主体数据验证开始..工务署实名制项目号:" + gwsProjectCode);
        // 主体信息
        if (yzwProjectCode == null || yzwProjectCode == 0) {
            IntelligentsiteCorrespondsItemtable intelligentsiteCorrespondsItemtable = intelligentsiteCorrespondsMapper
                    .selectOneRecordByProjectName(projectName);
            yzwProjectCode = intelligentsiteCorrespondsItemtable.getIntelligentsite_attendance_id();
        }
        if (yzwProjectCode == null) {
            log.error("工务署业务模块-上传人员到工务署-项目对应主体数据验证不通过.原因：平台表不存在standardProjectName字段或Intelligentsite_attendance_id为空："
                    + projectName);
            return "结束（跳过）";
        }

        // header密钥
        GwsPushData gwsPushData = gwsPushDataMapper.selectOneRecordByGwsProjectCode(gwsProjectCode);
        // header查找
        String api_key = gwsPushData.getApiKey();// √
        String api_secret = gwsPushData.getApiSecret();
        String client_serial = gwsPushData.getClientSerial();
        String api_version = gwsPushData.getApiVersion();
        String timestamp = DataUtil.currTime();

        if (detailedRecordLong) {
            log.info("工务署业务模块-上传考勤到工务署-上传主体验证通过");
            log.info("工务署业务模块-上传考勤到工务署-开始获取本机要上传的项目人员..");
            log.info("工务署业务模块-上传考勤到工务署-开始数据初始化..");
        }
        YzwProjectKeyAndCode ypk = yzwProjectKeyAndCodeMapper.findOneRecord(yzwProjectCode);
        String yzwProjectKey = ypk.getProjectKey();

        JSONObject catchDetailedJSON = new JSONObject();
        List catchDetailedArray = new ArrayList();
        int catchNum = 0;
        JSONObject catchNumJSON = new JSONObject();
        List catchNumArray = new ArrayList();

        int successInt = 0;
        JSONObject successJSON = new JSONObject();
        List successArray = new ArrayList();

        String imAge = null;
        String gwsImAgeId = null;

        // 所有在工务署库的工人信息
        // List<YzwWorkerList> gwl =
        // gwsCWRMapper.selectGwsWorkerListByGwsProjectCodeOrIdCardNumber(gwsProjectCode,
        // null);
        // 启用
        // false查询在册人数 true查询在场人数
        List<YzwWorkerList> gwl = gwsCWRMapper.selectPresenceOfWorkerList2(yzwProjectCode, false, "iDCardNumber");
        String a = JSONObject.toJSONString(gwl);
        if (gwl == null) {
            if (detailedRecordLong)
                log.info("工务署业务模块-上传考勤到工务署-获取本机要上传的项目人员完成,数据为空，即将结束该次会话");
            return "结束（跳过）";
        }
        if (detailedRecordLong)
            log.info("工务署业务模块-上传考勤到工务署-获取本机要上传的项目人员完成，获取到" + gwl.size() + "条人员记录");

        // 根据身份证号以及日期获得考勤信息
        List<YzwProjectAttendanceListNew> yzAl = null;
        String idCardNumber = null;
        String passedTime = null;
        String localSitePhoto = null;

        int yzAlCount = 0;

        String resultInfo = null;
        GwsProjectAttendanceListNew gwsProjectAttendanceListNew = new GwsProjectAttendanceListNew();

        // 直连云筑网查询
        YzwWorkerList findWorkDetailed = null;
        YzwBusinessUtil yzwBusinessUtil = new YzwBusinessUtil();
        if (detailedRecordLong) {
            log.info("工务署业务模块-上传考勤到工务署-数据初始化声明完成.");
            log.info("工务署业务模块-上传考勤到工务署-开始组装数据..");
            log.info("工务署业务模块-上传考勤到工务署-根据人员一个个循环上报考勤..");
        }
        for (int i = 0; i < gwl.size(); i++) {

            idCardNumber = (String) gwl.get(i).getIDCardNumber();

            if (detailedRecordLong) {
                log.info("工务署业务模块-上传考勤到工务署-获取身份证号为.." + idCardNumber + "的本地数据库今日考勤数据");
                log.info("工务署业务模块-上传考勤到工务署-根据身份证号在云筑网表进行查询获取个人详细信息...");
            }

            findWorkDetailed = yzwWorkerListMapper.findOneRecordByIdCardNumber(idCardNumber,
                    gwl.get(i).getProjectCode());

            if (findWorkDetailed == null) {
                log.error("工务署业务模块-上传考勤到工务署-跳过该人员考勤上传（因为yzwworkerlist表没有该人员）:" + idCardNumber);
                continue;
            }

            if (detailedRecordLong)
                log.info("工务署业务模块-上传考勤到工务署-根据身份证号在云筑网表进行查询获取个人详细信息完成！");

            // 直连or本地？
            if (directlyConnectedYzwPersonnelPassageData) {
                yzAl = directlyConnectedYzwPersonService.getAtt(yzwProjectCode, yzwProjectKey,
                        findWorkDetailed.getWorkerName(), DataUtil.todayZero(), DataUtil.currTime());
                if (yzAl == null) {
                    log.error("工务署业务模块-上传考勤到工务署-跳过该人员考勤上传（因为直连获取不到该人员考勤）:" + idCardNumber);
                    log.info("进度：" + successInt + "/" + yzAlCount + "\n\n");
                    continue;
                }
            } else {
                // 考勤信息 第二个参数空表示该身份证下的所有考勤信息，0表示今天的，1表示昨天的
                yzAl = gwsCWRMapper.selectAttendancelistnewByIDCardNumberAndConditionTime(idCardNumber, 0);
            }

            if (yzAl.size() == 0)
                log.info("工务署业务模块-上传考勤到工务署-获取到该人员考勤为空记录，该人员跳过上传:" + findWorkDetailed.getWorkerName());
            log.info("工务署业务模块-上传考勤到工务署-即将进入发送阶段，准备数据最后阶段...");
            for (int j = 0; j < yzAl.size(); j++) {
                // 直连的考勤考勤记录数据有T就要处理，本地的考勤数据是已经处理过的就不用过滤
                if (directlyConnectedYzwPersonnelPassageData) {
                    passedTime = yzAl.get(j).getTime();
                    // 转换为标准格式的时间以便发送到工务署
                    passedTime = yzwBusinessUtil.parseTimeTostandard(passedTime);
                } else {
                    passedTime = yzAl.get(j).getTime();
                }
                // List<GwsProjectAttendanceListNew> gwsPAListNewl = null;

                // 先不做通过gws_projectattendancelistnew的记录判断重复提交
                // // 查出是否提交过，通过3个字段辨别，工务署号、身份证号和打卡时间
                // gwsPAListNewl = gwsCWRMapper
                // .selectOneRecordProjectAttendanceListNewByProjectcodeAndIdAndPassedTime(gwsProjectCode,
                // idCardNumber, passedTime);

                // 总数量
                yzAlCount++;

                paramjson.put("Project_ID", gwsProjectCode);
                paramjson.put("Device_ID", yzAl.get(j).getSerialNumber());

                List<JSONObject> passedlog_list = new ArrayList<>();
                JSONObject passedlog = new JSONObject();
                passedlog.put("data_id", api_key + UUID.randomUUID().toString().replace("-", ""));// 数据的唯一id
                passedlog.put("person_type", "1");// 通行人员类型。0—临时人员（访客），1—员工
                passedlog.put("person_id", idCardNumber);
                passedlog.put("person_name", yzAl.get(j).getWorkerName());

                passedlog.put("passed_time", passedTime);

                if (yzAl.get(j).getType() == 1)
                    passedlog.put("direction", "in");
                else if (yzAl.get(j).getType() == 2)
                    passedlog.put("direction", "out");
                else {
                    if (detailedRecordLong)
                        log.error("工务署业务模块-上传考勤到工务署,本次跳过（因为异常：考勤通行记录不正确（既不是1也不是2）），身份证号:", idCardNumber);
                    log.info("进度：" + successInt + "/" + yzAlCount);
                    continue;
                }

                passedlog.put("way", "1"); // 通行方式 1—人脸识别

                log.info("工务署业务模块-上传考勤到工务署-即将进入发送阶段，准备数据最后阶段...上传考勤图片中..");
                gwsImAgeId = imgDealWithGetAttImgId(api_key, idCardNumber, passedTime, gwsProjectCode, yzwProjectCode,
                        yzAl.get(j).getImage());
                if (gwsImAgeId == null) {
                    log.info("工务署业务模块-上传考勤到工务署-跳过本次考勤循环，因为上传考勤图片失败");
                    log.info("进度：" + successInt + "/" + yzAlCount);
                    continue;
                }
                if (detailedRecordLong)
                    log.info("工务署业务模块-上传考勤到工务署-即将进入发送阶段，准备数据最后阶段...上传考勤图片完成..");

                passedlog.put("site_photo", gwsImAgeId);
                passedlog_list.add(passedlog);

                paramjson.put("passedlog_list", passedlog_list);
                log.info("工务署业务模块-上传考勤到工务署-即将进入发送阶段，开始发送数据");
                resultInfo = innerFormalGWSCWRService.UploadPassedLog(paramjson);

                String code = innerFormalGWSCWRService.parseResultsCode(resultInfo);
                String message = innerFormalGWSCWRService.parseResultsMessage(resultInfo);
                if ((code.equals("00"))) {
                    if (detailedRecordLong) {
                        log.info("工务署业务模块-上传考勤到工务署-发送数据完成，请求成功！");
                        log.info("工务署业务模块-上传考勤到工务署-记录进档该次发送..");
                    }
                    gwsProjectAttendanceListNew.setGws_projectcode(gwsProjectCode);
                    gwsProjectAttendanceListNew.setIdcardnumber(idCardNumber);
                    gwsProjectAttendanceListNew.setPassed_time(passedTime);
                    gwsProjectAttendanceListNew.setLocal_site_photo(localSitePhoto);
                    gwsProjectAttendanceListNew.setSite_photo(gwsImAgeId);
                    gwsCWRMapper.innerOneRecordProjectAttendance(gwsProjectAttendanceListNew);

                    successJSON.put("完成数量", successInt + "/" + yzAlCount);
                    log.info("完成：" + successInt);
                    log.info("--------------------------------------------------------\n\n");
                    successInt++;
                } else if ((code.equals("03") && (message.equals("人员信息不存在")))) {
                    catchDetailedJSON = new JSONObject();
                    catchDetailedJSON.put(innerFormalGWSCWRService.parseResultsMessage(resultInfo) + "，身份证号",
                            idCardNumber);
                    catchDetailedArray.add(catchDetailedJSON);
                    if (detailedRecordLong) {
                        log.info("工务署业务模块-上传考勤到工务署-发送数据完成，请求失败！" + catchDetailedJSON.toString());
                        log.info("请求体:" + paramjson);
                    }
                    successJSON.put("完成数量", successInt + "/" + yzAlCount);
                    log.info("完成：" + successInt);
                    log.info("--------------------------------------------------------\n\n");
                    // 在工务署不存在则跳过
                    break;
                } else if (!code.equals("00")) {
                    catchDetailedJSON.put(message + "，身份证号", idCardNumber);
                    catchDetailedArray.add(catchDetailedJSON);
                    if (detailedRecordLong) {
                        log.info("工务署业务模块-上传考勤到工务署-发送数据完成，请求失败！" + catchDetailedJSON.toString());
                        log.info("请求体:" + paramjson);
                    }
                    successJSON.put("完成数量", successInt + "/" + yzAlCount);
                    log.info("完成：" + successInt);
                    log.info("--------------------------------------------------------\n\n");
                }

            }
        }

        log.info("~~~~~~人员推送完成！完成/总数：" + successInt + "/" + yzAlCount);
        catchNumJSON.put("异常：yzw表没有，gws表有,总计/gws表总人数：", catchNum + "/" + gwl.size());
        catchDetailedArray.add(catchDetailedJSON);
        catchNumArray.add(catchNumJSON);
        log.info("未正常提交/处理的结果集合:" + catchDetailedArray.toString());

        successJSON.put("完成数量", successInt + "/" + yzAlCount);
        successArray.add(successJSON);
        log.info(successArray.toString());
        log.info(catchNumArray.toString());
        return "完成";

    }

    /**
     * 上传考勤
     *
     * @throws Exception
     */
    public void uploadPersonnelPassageData2(Boolean directlyConnectedYzwPersonnelPassageData, String gwsProjectCode,
                                            Integer yzwProjectCode, String projectName) {

        if (StringUtils.isEmpty(gwsProjectCode) || yzwProjectCode == null || StringUtils.isEmpty(projectName)) {
            return;
        }
        JSONObject paramjson = new JSONObject();
        // header密钥
        GwsPushData gwsPushData = gwsPushDataMapper.selectOneRecordByGwsProjectCode(gwsProjectCode);
        // header查找
        String api_key = gwsPushData.getApiKey();// √

        List<GwsAttendanceDTO> att = null;
        List<String> attDevice = gwsCWRMapper.findBySerialNumberGroup(yzwProjectCode);

        if (attDevice == null || attDevice.isEmpty()) {
            log.info("工务署业务模块-上传考勤到工务署-获取本机要上传的项目人员完成,数据为空，即将结束该次会话");
            return;
        }
        GwsAttendanceDTO gwsAtt = new GwsAttendanceDTO();

        String serialNumber = "";

        int succeedNum = 0;
        List<String> errors = new ArrayList<>();

        int total = 0;
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < attDevice.size(); i++) {

            serialNumber = attDevice.get(i);

            paramjson.put("Project_ID", gwsProjectCode);
            paramjson.put("Device_ID", serialNumber);

            att = gwsCWRMapper.findByDbTodarAttendance(serialNumber);

            if (att == null || att.isEmpty())
                continue;

            total += att.size();

            for (GwsAttendanceDTO gwsAttendanceDTO : att) {

                if(gwsAttendanceDTO.getStatus() == 1 || gwsAttendanceDTO.getProjectCode() != yzwProjectCode){
                    System.out.println("--------------------------------------已经为上传了 ---------------------了上传失败------------------------------------------------");
                    continue;
                }

//                if(true){
//                    System.out.println("进入了");
//                    return;
//                }

                // 人员考情信息组装
                List<JSONObject> passedlog_list = new ArrayList<>();

                gwsAtt = gwsAttendanceDTO;
                gwsAtt.setData_id(api_key + UUID.randomUUID().toString().replace("-", ""));

                String gwsImAgeId = null;

                try {
                    gwsImAgeId = imgDealWithGetAttImgId(api_key, gwsAtt.getPerson_id(), gwsAtt.getPassed_time(),
                            gwsProjectCode, yzwProjectCode, gwsAtt.getSite_photo());

                    if (StringUtils.isEmpty(gwsImAgeId))
                        continue;

                    gwsAtt.setSite_photo(gwsImAgeId);

                    passedlog_list.add(JSONObject.parseObject(JSON.toJSONString(gwsAtt)));

                    paramjson.put("passedlog_list", passedlog_list);

                    // 发送考勤到
                    String res = innerFormalGWSCWRService.UploadPassedLog(paramjson);
                    String code = innerFormalGWSCWRService.parseResultsCode(res);
                    String message = innerFormalGWSCWRService.parseResultsMessage(res);

                    if (("00").equals(code)) {
                        int i1 = gwsCWRMapper.updateStatus(gwsAttendanceDTO.getPerson_id(), gwsAttendanceDTO.getPassed_time());
                        System.out.println(i1+"---------------->>>>修改成功<<<<-----------------------"+gwsAttendanceDTO);
                        list.add(gwsAttendanceDTO.getPerson_name());
                        succeedNum++;
                    } else {
                        errors.add(gwsAtt.getPerson_id() + message);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }
        System.out.println(list.toString());
        // log.info("总数/成功：" + total + "/" + succeedNum);
        // log.error(JSONArray.toJSONString(errors.toString()));
    }

    /**
     * 根据项目号或工人名字确定人员离场 String standardProjectName = "十五高级中学";
     * //不填WorkName则查整个项目出来 可修改为你需要改成的库表内的【标准项目名】
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    public void personnelLeaveProjectByStandardProjectNameOrWorkerName(String standardProjectName, String WorkerName) {

        // step0、获取主体 方面的数据前准备
        // ------------start

        ModuleDetailedCorrespondingProject moduleDetailedCorrespondingProject = moduleDetailedCorrespondingProjectNoMapper
                .selectOneRecordByStandardProjectName(standardProjectName);

        if (moduleDetailedCorrespondingProject == null) {
            log.info("平台表（moduleDetailedCorrespondingProject）不存该项目：" + standardProjectName);
            return;
        }

        String gwsRealNameSystemProjectCode = moduleDetailedCorrespondingProject.getGwsRealNameSystemProjectCode();
        if (gwsRealNameSystemProjectCode == null || gwsRealNameSystemProjectCode.equals("")) {
            log.info("平台表（moduleDetailedCorrespondingProject）不存在工务署项目id：" + standardProjectName);
            return;
        }
        IntelligentsiteCorrespondsItemtable intelligentsiteCorrespondsItemtable = intelligentsiteCorrespondsMapper
                .selectOneRecordByStandardProjectName(standardProjectName);
        Integer yzwProjectCode = intelligentsiteCorrespondsItemtable.getIntelligentsite_attendance_id();

        if (yzwProjectCode == null) {
            log.info("平台表不存在standardProjectName字段或Intelligentsite_attendance_id为空，项目标准名：" + standardProjectName);
            return;
        }

        List<YzwWorkerList> yl = gwsCWRMapper
                .selectGwsWorkerListByGwsProjectCodeOrIdCardNumber(gwsRealNameSystemProjectCode, WorkerName);

        log.info("yzwWorkerList:" + yl.size());

        // ------------end

        JSONObject paramjson = new JSONObject();
        List<JSONObject> userLeaveProject_list = new ArrayList<>();
        JSONObject passedlog = new JSONObject();

        JSONObject catchJSON = new JSONObject();
        List catchArray = new ArrayList();
        int successInt = 0;
        JSONObject successJSON = new JSONObject();
        List successArray = new ArrayList();

        String resultInfo = "";
        String iDCardNumber = "";

        for (YzwWorkerList yzwWorkerList : yl) {
            iDCardNumber = yzwWorkerList.getIDCardNumber();

            paramjson.put("Project_ID", gwsRealNameSystemProjectCode);

            userLeaveProject_list.clear();
            passedlog.clear();
            passedlog.put("id_code", iDCardNumber);
            passedlog.put("exit_time", DataUtil.currTime());
            // passedlog.put("exit_time", "2021-05-13 16:26:15");
            passedlog.put("SUID", yzwWorkerList.getYzwSubContractorList().getSocialCreditNumber());
            userLeaveProject_list.add(passedlog);

            paramjson.put("userLeaveProject_list", userLeaveProject_list);

            resultInfo = innerFormalGWSCWRService.userLeaveProject(paramjson);
            if (!innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00")) {
                log.info("未完成操作，请求体:" + paramjson + "。\n请求结果："
                        + innerFormalGWSCWRService.parseResultsMessage(resultInfo));
            } else if ((innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00"))) {
                if (gwsWorkerlistMapper.deleteGwsWorkerlistOneRecordByIdCardNumber(iDCardNumber) == 0) {
                    catchJSON.put("已经在工务署离场该人员，但在本机表记录没有发现身份证号为", iDCardNumber + "的人员");
                    catchArray.add(catchJSON);
                    // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
                    continue;
                }
                successInt++;
                successJSON.put("完成数量", successInt);
                successArray.add(successJSON);
            }
        }

    }

    /**
     * 根据身份证号号确定人员离场 String standardProjectName = "十五高级中学"; //
     * 可修改为你需要改成的库表内的【标准项目名】
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    public void personnelLeaveProjectByIdCardNumber(String IdCardNumber) {

        YzwWorkerList yw = gwsCWRMapper.selectGwsWorkerListByGwsIdCardNumber(IdCardNumber);

        // ------------end

        JSONObject paramjson = new JSONObject();
        List<JSONObject> userLeaveProject_list = new ArrayList<>();
        JSONObject passedlog = new JSONObject();

        JSONObject catchJSON = new JSONObject();
        List catchArray = new ArrayList();
        int successInt = 0;
        JSONObject successJSON = new JSONObject();
        List successArray = new ArrayList();

        String resultInfo = "";
        String iDCardNumber = "";
        String gwsRealNameSystemProjectCode = yw.getGwsWorkerlist().getGws_projectcode();

        iDCardNumber = yw.getIDCardNumber();

        paramjson.put("Project_ID", gwsRealNameSystemProjectCode);

        userLeaveProject_list.clear();
        passedlog.clear();
        passedlog.put("id_code", iDCardNumber);
        passedlog.put("exit_time", DataUtil.currTime());
        // passedlog.put("exit_time", "2021-05-13 16:26:15");
        passedlog.put("SUID", yw.getYzwSubContractorList().getSocialCreditNumber());
        userLeaveProject_list.add(passedlog);

        paramjson.put("userLeaveProject_list", userLeaveProject_list);

        resultInfo = innerFormalGWSCWRService.userLeaveProject(paramjson);
        if (!innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00")) {
            log.info("未完成操作，请求体:" + paramjson + "。\n请求结果：" + innerFormalGWSCWRService.parseResultsMessage(resultInfo));
        } else if ((innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00"))) {
            if (gwsWorkerlistMapper.deleteGwsWorkerlistOneRecordByIdCardNumber(iDCardNumber) == 0) {
                catchJSON.put("已经在工务署离场该人员，但在本机表记录没有发现身份证号为", iDCardNumber + "的人员");
                catchArray.add(catchJSON);
            }
            successInt++;
            successJSON.put("完成数量", successInt);
            successArray.add(successJSON);
        }
        log.error(catchArray.toString());
        log.info(successArray.toString());

    }

    /**
     * 手动上传离场 String standardProjectName = "十五高级中学"; // 可修改为你需要改成的库表内的【标准项目名】
     */
    public void manualPersonnelLeaveProject(String gwsRealNameSystemProjectCode, String iDCardNumber, String SUID) {

        // ------------end

        JSONObject paramjson = new JSONObject();
        List<JSONObject> userLeaveProject_list = new ArrayList<>();
        JSONObject passedlog = new JSONObject();

        JSONObject catchJSON = new JSONObject();
        List catchArray = new ArrayList();
        int successInt = 0;
        JSONObject successJSON = new JSONObject();
        List successArray = new ArrayList();

        String resultInfo = "";

        paramjson.put("Project_ID", gwsRealNameSystemProjectCode);
        passedlog.put("id_code", iDCardNumber);
        passedlog.put("exit_time", DataUtil.currTime());
        passedlog.put("SUID", SUID);
        userLeaveProject_list.add(passedlog);

        paramjson.put("userLeaveProject_list", userLeaveProject_list);

        resultInfo = innerFormalGWSCWRService.userLeaveProject(paramjson);
        if (!innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00")) {
            log.info("未完成操作，请求体:" + paramjson + "。\n请求结果：" + innerFormalGWSCWRService.parseResultsMessage(resultInfo));
        } else if ((innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00"))) {
            if (gwsWorkerlistMapper.deleteGwsWorkerlistOneRecordByIdCardNumber(iDCardNumber) == 0) {
                catchJSON.put("已经在工务署离场该人员，但在本机表记录没有发现身份证号为", iDCardNumber + "的人员");
                catchArray.add(catchJSON);
            }
            successInt++;
            successJSON.put("完成数量", successInt);
            successArray.add(successJSON);
        }
        log.error(catchArray.toString());
        log.info(successArray.toString());

    }

    /**
     * 上传人员
     *
     * @throws ParseException
     * @throws NoSuchAlgorithmException
     */
    // @Transactional(propagation = Propagation.REQUIRED,readOnly =
    // false,rollbackFor=Exception.class)
    public String uploadPersonnelBaseInfo(String gwsProjectCode, Integer yzwProjectCode, String projectName) {

        GwsCorYzwTeam gwsCorYzwTeam = null;
        JSONObject paramjson = new JSONObject();
        String resultInfo = "";
        if ((verifyTheAuthorization(yzwProjectCode, projectName) == null))
            return "结束（跳过）";
        List<YzwWorkerList> yl = getPerData(yzwProjectCode);

        // header密钥
        GwsPushData gwsPushData = gwsPushDataMapper.selectOneRecordByGwsProjectCode(gwsProjectCode);
        if (gwsPushData == null) {
            log.error("没有获取到密钥，跳过");
            return "结束（跳过）";
        }

        LocalDateTime a = LocalDateTime.now();

        String time = a.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // header查找
        String api_key = gwsPushData.getApiKey();// √
        String api_secret = gwsPushData.getApiSecret();
        String client_serial = gwsPushData.getClientSerial();
        String api_version = gwsPushData.getApiVersion();
        String timestamp = time;

        log.info("工务署业务模块-上传人员到工务署-开始组装数据..");
        GwsWorkerlist gwsWorkerlist = new GwsWorkerlist();
        GwsWorkerlist storeGwsWorkerlist = new GwsWorkerlist();
        GwsDictListJobName gwsDictListJobName = null;
        YzwSubContractorList yzwSubContractorList = null;
        GwsPerson gwsPerson = null;
        GwsTeam gwsTeam = null;

        // param
        // 工人名
        String workName = null;
        String yzwWorkTypeName = null;
        // 当前记录下的工人班组
        String subContractorName = null;
        String headImagePathId = null;
        String issueCardPicid = null;
        String suid = null;
        String jobOrder = "";
        String jobName = "";
        String teamId = "";
        String teamName = "";
        String empPhone = "";
        String empNativePlace = "";
        String empNation = "";
        // 捕获异常存放信息的变量
        int successInt = 0;

        if (detailedRecordLong)
            log.info("工务署业务模块-上传人员到工务署-进入人员一个个循环上报..");
        for (YzwWorkerList yzwWorkerList : yl)
            try {
                if(yzwWorkerList.getStatus() == 1){
                    System.out.println("<<<<<<<<<<<<<<<<-----------------人员已经上传过-------------------->>>>>>>>>>>>>>>>>>>>>>>>");
                    continue;
                }
                    String idCardNumber = yzwWorkerList.getIDCardNumber();

                    if (detailedRecordLong)
                        log.info("工务署业务模块-上传人员到工务署-开始查询人员是否已经上报..");
                    gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
                    // 通过身份证号从表获取
                    if (gwsPerson == null || gwsPerson.getHeadImagePathId() == null
                            || gwsPerson.getIssueCardPicId() == null) {
                        if (detailedRecordLong)
                            log.info("工务署业务模块-上传人员到工务署-人员未上报.即将开始上报头像和身份证图片");
                        // 如若没有就上传获得id，然后存储进表
                        // 上传近身及头像照片及获取返回的图片id
                        if (detailedRecordLong)
                            log.info("工务署业务模块-上传人员到工务署-开始上报头像图片...");
                        headImagePathId = imgDealWithGetHeadPathId(api_key, idCardNumber, yzwProjectCode,
                                yzwWorkerList.getHeadImagePath());
                        if (StringUtils.isEmpty(headImagePathId)) {
                            log.info("工务署业务模块-上传人员到工务署-上报头像结果为空，该人员跳过上报人员信息." + yzwWorkerList.getHeadImagePath());
                            log.info("完成/总数量：" + successInt + "/" + yl.size());
                            continue;
                        }
                        if (detailedRecordLong) {
                            log.info("工务署业务模块-上传人员到工务署-上报头像图片完成.");
                            log.info("工务署业务模块-上传人员到工务署-开始上报身份证照片...");
                        }
                        issueCardPicid = imgDealWithGetIssueCardPicId(api_key, idCardNumber, yzwProjectCode,
                                yzwWorkerList.getIssueCardPicPath());
                        if (StringUtils.isEmpty(issueCardPicid)) {
                            log.info("工务署业务模块-上传人员到工务署-上报头像结果为空，该人员跳过上报人员信息." + yzwWorkerList.getHeadImagePath());
                            log.info("完成/总数量：" + successInt + "/" + yl.size());
                            continue;
                        }
                        if (detailedRecordLong) {
                            log.info("工务署业务模块-上传人员到工务署-上报头像图片完成.");
                            log.info("工务署业务模块-上传人员到工务署-开始组装参数体..");
                        }
                    }

                    gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
                    headImagePathId = gwsPerson.getHeadImagePathId();
                    issueCardPicid = gwsPerson.getIssueCardPicId();
                    // 接口入参map 方式
                    paramjson.put("Project_ID", gwsProjectCode);
                    paramjson.put("id_code", idCardNumber);

                    workName = yzwWorkerList.getWorkerName();
                    empPhone = yzwWorkerList.getCellphone();
                    empNativePlace = yzwWorkerList.getAddress();
                    empNation = yzwWorkerList.getNation();
                    // gwsWorkerlist =
                    // gwsWorkerlistMapper.selectByGWSIdCardNumber(idCardNumber);
                    paramjson.put("id_photo", headImagePathId);
                    paramjson.put("emp_name", workName);
                    paramjson.put("emp_phone", empPhone);
                    paramjson.put("emp_nativeplace", empNativePlace);
                    paramjson.put("emp_nation", empNation + "族");
                    paramjson.put("match_flag", "Y");
                    if (StringUtils.isEmpty(issueCardPicid))
                        issueCardPicid = "暂空";
                    paramjson.put("facephoto", issueCardPicid);
                    paramjson.put("id_agency", "暂无");// 签发机关

                    // 赋值公司名（云筑网分包商名）及营业执照号
                    log.info("工务署业务模块-上传人员到工务署-组装参数体-分包商获取开始");
                    try {
                        yzwSubContractorList = yzwSubContractorListMapper
                                .findOneRecordBySysNo(yzwWorkerList.getSubContractorSysNo(), yzwProjectCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (yzwSubContractorList == null) {
                        log.info("工务署业务模块-上传人员到工务署-组装参数体-分包商获取为空.跳过本次人员，进入下一个人员..");
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }
                    subContractorName = yzwSubContractorList.getSubContractorName();
                    if (subContractorName == null) {
                        log.info("工务署业务模块-上传人员到工务署-组装参数体-企业名没有.跳过本次人员，进入下一个人员..");
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }
                    paramjson.put("emp_company", subContractorName);
                    suid = yzwSubContractorList.getSocialCreditNumber();
                    if (StringUtils.isEmpty(issueCardPicid)) {
                        log.info("工务署业务模块-上传人员到工务署-组装参数体-企业营业执照号没有.跳过本次人员，进入下一个人员..");
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }
                    paramjson.put("SUID", suid);

                    // gwsCorYzwTeam =
                    // gwsCorYzwTeamMapper.selectOneRecordByYzwProjectCodeAndYzwTeamSysNo(yzwProjectCode,
                    // yzwWorkerList.getTeamSysNo());
                    teamName = yzwTeamMasterMapper.findOneRecordByTeamSysNo(yzwWorkerList.getTeamSysNo()).getTeamName();
                    gwsTeam = gwsCWRMapper.findOneRecordByYzwTeamNameAndSUID(teamName, suid);
                    // 赋值团队/班组号
                    if (StringUtils.isEmpty(gwsTeam)) {
                        log.error("操作跳过，因为在表gws_team没有找到记录(该人员所在的班组未上传):" + teamName + "," + subContractorName);
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }
                    teamId = gwsTeam.getGws_teamid();
                    teamName = gwsTeam.getGws_teamname();
                    if (StringUtils.isEmpty(teamId) || StringUtils.isEmpty(teamName)) {
                        log.error("操作跳过，因为在表gws_team没有找到teamId或teamName记录(该人员所在的班组未上传):" + teamName + ","
                                + subContractorName);
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }

                    paramjson.put("team_id", teamId);
                    paramjson.put("team_name", teamName);
                    paramjson.put("emp_category", "00"); // 人员类型 (00: 建筑工人)

                    // 工种号
                    yzwWorkTypeName = yzwWorkerList.getWorkTypeName();
                    gwsDictListJobName = gwsCWRMapper.selectGwsDictListByLikeValue(yzwWorkTypeName);
                    if (gwsDictListJobName != null) {
                        jobOrder = gwsDictListJobName.getOrders();
                        jobName = gwsDictListJobName.getValue();
                    } else {
                        // if (yzwWorkTypeName.contains("管理")) {
                        // gwsDictListJobName根本包含管理的
                        jobOrder = "39";
                        jobName = "其它";
                        // } else {
                        // log.info("操作跳过，因为云筑网的该工种：" + yzwWorkTypeName +
                        // "在表gws_dictlist_jobname没有找到");
                        // log.info("完成/总数量：" + successInt + "/" + yl.size());
                        // continue;
                        // }
                    }
                    paramjson.put("job_order", jobOrder);
                    paramjson.put("job_name", jobName);
                    paramjson.put("contract_status", "1");

                    resultInfo = innerFormalGWSCWRService.RegisterEmployee(paramjson, api_secret, api_key, api_version,
                            client_serial, timestamp);
                    if (StringUtils.isEmpty(resultInfo)) {
                        log.error("获取结果时出错。跳过获取结果，继续上报下一条");
                        log.info("完成/总数量：" + successInt + "/" + yl.size());
                        continue;
                    }
                    if ((innerFormalGWSCWRService.parseResultsCode(resultInfo).equals("00")
                            && innerFormalGWSCWRService.parseResultsMessage(resultInfo).equals("成功"))
                            || innerFormalGWSCWRService.parseResultsMessage(resultInfo).equals("此人员已经在此工程")) {
                        storeGwsWorkerlist.setGws_projectcode(gwsProjectCode);
                        storeGwsWorkerlist.setIdcardnumber(idCardNumber);
                        storeGwsWorkerlist.setGws_issuecardpicid(issueCardPicid);
                        storeGwsWorkerlist.setGws_headImageid(headImagePathId);
                        storeGwsWorkerlist.setSUID(suid);
                        int i = yzwWorkerListMapper.updateStatus(yzwWorkerList.getIDCardNumber());
                        System.out.println("修改成功--------------->>>"+i);
                        // 存储进表
                        gwsWorkerlistMapper.innerOneRecord(storeGwsWorkerlist);
                        successInt++;
                    } else {
                        log.error("发起工务署的请求失败，请求体:" + paramjson);
                        log.error("请求结果:" + innerFormalGWSCWRService.parseResultsMessage(resultInfo));
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        log.info("~~~~~~人员推送完成！完成/总数：" + successInt + "/" + yl.size());
        return "完成";
    }

    /**
     * 上传班组 备：如果返回显示 班组的名称重复，那么请检查gws_team有没有该记录
     */
    public void uploadTeam(String gwsProjectCode, Integer yzwProjectCode, String projectName) {

        // header密钥
        GwsPushData gwsPushData = gwsPushDataMapper.selectOneRecordByGwsProjectCode(gwsProjectCode);
        if (gwsPushData == null) {
            return;
        }
        // header查找
        String api_key = gwsPushData.getApiKey();// √
        String api_secret = gwsPushData.getApiSecret();
        String client_serial = gwsPushData.getClientSerial();
        String api_version = gwsPushData.getApiVersion();
        String timestamp = DataUtil.currTime();

        // 没有入场的参建单位统计
        List<Object> noSubStatistical = new ArrayList<>();
        // 没有上传或gws_team表没有的
        Map<Object, Object> noUploadTeamStatisticalMap = new HashMap<>();
        List<Object> noUploadTeamStatistical = new ArrayList<>();

        List<GwsAndYzwTeamDao> gwsCorYzwTeams = gwsAndYzwTeamDaoMapper.findByGwsTeam(yzwProjectCode);

        int succCount = 0;

        JSONObject json = new JSONObject(true);

        String tableTeamId = "";

        String tableTeamName = "";

        for (GwsAndYzwTeamDao corYzwTeam : gwsCorYzwTeams) {
            System.out.println("输出的值为---->>>>>"+corYzwTeam.toString());
            if(corYzwTeam.getStatus() == 1){
                System.out.println("<<<<<<<---------------该班次已上传----------------------->>>>>>>>>>>>>>>>>");
                continue;
            }
            String SUID = corYzwTeam.getSUID();
            String empCompany = corYzwTeam.getEmp_company();
            String teamTypeOrder = corYzwTeam.getTeam_type_order();
            String teamTypeName = corYzwTeam.getTeam_type_name();
            String teamName = corYzwTeam.getTeam_name();

            json.put("Project_ID", gwsProjectCode);
            json.put("team_type_order", teamTypeOrder);// 3.1.4接口
            json.put("team_type_name", teamTypeName);// 3.1.4接口
            json.put("team_name", teamName);
            json.put("emp_company", empCompany);
            json.put("SUID", SUID);

            String resultInfo = innerFormalGWSCWRService.addTeam(json, api_secret, api_key, api_version, client_serial,
                    timestamp);

            String resultCode = innerFormalGWSCWRService.parseResultsCode(resultInfo);
            if (resultCode == null) {
                noSubStatistical.add(teamName + "班组上次失败");
                continue;
            }
            String resultMessage = innerFormalGWSCWRService.parseResultsMessage(resultInfo);
            if (resultMessage.equals("成功") && resultCode.equals("00")) {

                tableTeamId = JSONObject.parseObject(innerFormalGWSCWRService.parseResultsData(resultInfo))
                        .getString("team_id");
                tableTeamName = JSONObject.parseObject(innerFormalGWSCWRService.parseResultsData(resultInfo))
                        .getString("team_name");
                gwsCWRMapper.innerOneTeamRecord(gwsProjectCode, tableTeamId, tableTeamName, empCompany, SUID);
                int i = gwsAndYzwTeamDaoMapper.updateStatus(corYzwTeam.getTeam_sysno());
                System.out.println("<<<<<<<<<<<<-------------------已经上传的班次有---------->>>>>>>>>"+i);
                succCount++;
            } else if ((resultMessage.equals("查询不到企业信息") || resultMessage.equals("企业未入场，不能创建班组"))
                    && resultCode.equals("03")) {
                noSubStatistical.add(SUID + "企业未入场，不能创建班组");
            } else if (resultMessage.equals("班组的名称重复") && resultCode.equals("03")) {
                GwsTeam gwsTeam = gwsCWRMapper.findOneRecordByYzwTeamNameAndSUID(tableTeamName, SUID);
                if (gwsTeam == null) {
                    noUploadTeamStatisticalMap = new HashMap<>();
                    noUploadTeamStatisticalMap.put("gws_projectcode", gwsProjectCode);
                    noUploadTeamStatisticalMap.put("gws_teamname", tableTeamName);
                    noUploadTeamStatisticalMap.put("emp_company", empCompany);
                    noUploadTeamStatisticalMap.put("SUID", SUID);
                    gwsCWRMapper.innerOneTeamRecord(gwsProjectCode, tableTeamId, tableTeamName, empCompany, SUID);
                    noUploadTeamStatistical.add(noUploadTeamStatisticalMap + "班组的名称重复");
                } else {
                    succCount++;
                }
            }
        }
        // log.info("班组推送完成！已同步/总数：" + succCount + "/" + gwsCorYzwTeams.size());
        // log.info("上次失败记录：" + noSubStatistical.toString());
        // log.info("上传了未保存在本地的班组有：" +
        // JSONObject.toJSONString(noUploadTeamStatistical));
    }

    // 解析然后下载远程图片到本地并上传图片、然后更新是本机工务署的表记录
    public void uploadPhotoAndStoreToProjectPersonnel(Integer yzwProjectCode) {
        // 所有人员信息
        List<YzwWorkerList> wl = gwsCWRMapper.selectPresenceOfWorkerList(yzwProjectCode, "iDCardNumber");
        HttpGet httpGet = new HttpGet();

        String headImagePath = null;
        String issueCardPicPath = null;

        String localhostHeadImagePath = null;
        String localhostIssueCardPicPath = null;
        String localhostBaseUrl = "D:\\uploadGwsStoreYzwImg\\yzwworkerlist\\";
        int count = 0;

        int catchInt = 0;
        JSONObject catchJSON = new JSONObject();
        List catchArray = new ArrayList();

        File file = new File(localhostBaseUrl);
        if (!file.exists()) { // 判断文件路径是否存在
            file.mkdirs(); // 不存在创建新的文件
        }

        for (YzwWorkerList yzwWorkerList : wl) {
            headImagePath = "";
            issueCardPicPath = "";

            localhostHeadImagePath = "";
            localhostIssueCardPicPath = "";

            // 获取头像照网络地址
            headImagePath = yzwWorkerList.getHeadImagePath();
            // 获取近身照网络地址
            issueCardPicPath = yzwWorkerList.getIssueCardPicPath();

            try {
                // 解析成为本地路径的文件名
                localhostHeadImagePath = headImagePath.substring(headImagePath.lastIndexOf("/") + 1);
                localhostIssueCardPicPath = issueCardPicPath.substring(headImagePath.lastIndexOf("/") + 1);
            } catch (Exception e) {
                catchInt++;
                continue;

            }

            localhostHeadImagePath = localhostBaseUrl + localhostHeadImagePath;
            localhostIssueCardPicPath = localhostBaseUrl + localhostIssueCardPicPath;

            // 添加至下载列表
            httpGet.addItem(headImagePath, localhostHeadImagePath);
            httpGet.addItem(issueCardPicPath, localhostIssueCardPicPath);
            // 开始下载
            httpGet.downLoadByList();
            httpGet.resetList();

            // 下载完成更新表记录
            count += gwsCWRMapper.updateLocalImageByIDCardNumber(localhostHeadImagePath, localhostIssueCardPicPath,
                    yzwWorkerList.getIDCardNumber());
            log.info("完成/总计：" + count + "/" + wl.size());

            catchJSON.put("localhostHeadImagePath为空,个数：", catchInt);
            catchArray.add(catchJSON);
            log.error("失败/总计：" + catchInt + "/" + wl.size());
        }

    }

    // 上传并保存单个人员照片 (已废弃)
    public void uploadPhotoAndStoreToAlonePersonnel(String iDCardNumber) {
        iDCardNumber = "";
        // 单个人员信息
        YzwWorkerList yzwWorker = yzwWorkerListMapper.findOneRecordByIdCardNumber(iDCardNumber, null);
        HttpGet httpGet = new HttpGet();

        String headImagePath = null;
        String issueCardPicPath = null;

        String localhostHeadImagePath = null;
        String localhostIssueCardPicPath = null;
        String localhostBaseUrl = "D:\\uploadGwsStoreYzwImg\\yzwworkerlist\\";
        int count = 0;

        int catchInt = 0;
        JSONObject catchJSON = new JSONObject();
        List catchArray = new ArrayList();

        File file = new File(localhostBaseUrl);
        if (!file.exists()) { // 判断文件路径是否存在
            file.mkdirs(); // 不存在创建新的文件
        }

        headImagePath = "";
        issueCardPicPath = "";

        localhostHeadImagePath = "";
        localhostIssueCardPicPath = "";

        // 获取头像照网络地址
        headImagePath = yzwWorker.getHeadImagePath();
        // 获取近身照网络地址
        issueCardPicPath = yzwWorker.getIssueCardPicPath();

        try {
            // 解析成为本地路径的文件名
            localhostHeadImagePath = headImagePath.substring(headImagePath.lastIndexOf("/") + 1);
            localhostIssueCardPicPath = issueCardPicPath.substring(headImagePath.lastIndexOf("/") + 1);
        } catch (Exception e) {
            catchInt++;
        }

        localhostHeadImagePath = localhostBaseUrl + localhostHeadImagePath;
        localhostIssueCardPicPath = localhostBaseUrl + localhostIssueCardPicPath;

        // 添加至下载列表
        httpGet.addItem(headImagePath, localhostHeadImagePath);
        httpGet.addItem(issueCardPicPath, localhostIssueCardPicPath);
        // 开始下载
        httpGet.downLoadByList();
        httpGet.resetList();

        // 下载完成更新表记录
        count += gwsCWRMapper.updateLocalImageByIDCardNumber(localhostHeadImagePath, localhostIssueCardPicPath,
                yzwWorker.getIDCardNumber());
        log.info("完成/总计：" + count + "/" + 1);

        catchJSON.put("localhostHeadImagePath为空,个数：", catchInt);
        catchArray.add(catchJSON);
        log.error("失败/总计：" + catchInt + "/" + 1);

    }

    // 图片处理-获取考勤照片id attImgInlinePath是在线图片地址
    public String imgDealWithGetAttImgId(String apiKey, String idCardNumber, String passedTime, String gwsProjectCode,
                                         Integer yzwProjectCode, String attImgInlinePath) {
        // 直接根据在线打卡照片路径查找是否已经上传，已经上传就获得，否则提交新的
        if (attImgInlinePath == null)
            return null;
        GwsProjectAttendanceListNew gwsProjectAttendanceListNew = gwsCWRMapper
                .selectOneRecordAttendance(attImgInlinePath);
        if (gwsProjectAttendanceListNew != null
                && !StringUtils.isEmpty(gwsProjectAttendanceListNew.getSite_photo()))
            return gwsProjectAttendanceListNew.getSite_photo();
        String attImgPathInd = null;
        String localAttImgPath = null;
        // 转换为jpeg，不需要
        // localAttImgPath =
        // StoreFileUtil.storeAttImgAndChangeNeedType(yzwProjectCode,
        // attImgInlinePath);
        localAttImgPath = StoreFileUtil.storeAttImg(yzwProjectCode, attImgInlinePath);
        if (StringUtils.isEmpty(localAttImgPath))
            return "";

        attImgPathInd = innerFormalGWSCWRService.UploadImage(apiKey, localAttImgPath);
        gwsProjectAttendanceListNew = new GwsProjectAttendanceListNew();
        gwsProjectAttendanceListNew.setGws_projectcode(gwsProjectCode);
        gwsProjectAttendanceListNew.setIdcardnumber(idCardNumber);
        gwsProjectAttendanceListNew.setSite_photo(attImgPathInd);
        gwsProjectAttendanceListNew.setPassed_time(passedTime);
        gwsProjectAttendanceListNew.setLocal_site_photo(localAttImgPath);
        gwsProjectAttendanceListNew.setRemote_site_photo(attImgInlinePath);
        gwsCWRMapper.innerOneRecordProjectAttendance(gwsProjectAttendanceListNew);
        return attImgPathInd;
    }

    // 图片处理-获取考勤照片id attImgInlinePath是在线图片地址
    public String imgDealWithGetAttImgId(String apiKey, String idCardNumber, String passedTime, String gwsProjectCode,
                                         String projectGuid, String attImgInlinePath) {
        // 直接根据在线打卡照片路径查找是否已经上传，已经上传就获得，否则提交新的
        if (attImgInlinePath == null)
            return null;
        GwsProjectAttendanceListNew gwsProjectAttendanceListNew = gwsCWRMapper
                .selectOneRecordAttendance(attImgInlinePath);

        if (gwsProjectAttendanceListNew != null && !StringUtils.isEmpty(gwsProjectAttendanceListNew.getSite_photo()))
            return gwsProjectAttendanceListNew.getSite_photo();

        String attImgPathInd = null;
        String localAttImgPath = null;
        // 转换为jpeg，不需要
        // localAttImgPath =
        // StoreFileUtil.storeAttImgAndChangeNeedType(yzwProjectCode,
        // attImgInlinePath);
        localAttImgPath = StoreFileUtil.storeYfAttImg(projectGuid, attImgInlinePath);
        if (StringUtils.isEmpty(localAttImgPath))
            return "";
        attImgPathInd = innerFormalGWSCWRService.UploadImage(apiKey, localAttImgPath);
        gwsProjectAttendanceListNew = new GwsProjectAttendanceListNew();
        gwsProjectAttendanceListNew.setGws_projectcode(gwsProjectCode);
        gwsProjectAttendanceListNew.setIdcardnumber(idCardNumber);
        gwsProjectAttendanceListNew.setSite_photo(attImgPathInd);
        gwsProjectAttendanceListNew.setPassed_time(passedTime);
        gwsProjectAttendanceListNew.setLocal_site_photo(localAttImgPath);
        gwsProjectAttendanceListNew.setRemote_site_photo(attImgInlinePath);
        gwsCWRMapper.innerOneRecordProjectAttendance(gwsProjectAttendanceListNew);
        return attImgPathInd;
    }

    // 图片处理-获取近身照id issueInlineCardPic是在线图片地址
    public String imgDealWithGetIssueCardPicId(String apiKey, String idCardNumber, Integer yzwProjectCode,
                                               String issueInlineCardPic) {
        GwsPerson gwsPerson = null;
        String issueCardPicId = null;
        String localissueCardPicPath = null;
        // 查询本地表是否保存有
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        // 表没有该人员记录或者图片路径为空的情况：下载云筑网在线图片然后上传工务署，然后保存
        if (gwsPerson == null || gwsPerson.getLocalIssueCardPicPath() == null) {
            localissueCardPicPath = StoreFileUtil.storePersonIssueImg(yzwProjectCode, issueInlineCardPic);
            if (localissueCardPicPath == null)
                return "";
            issueCardPicId = innerFormalGWSCWRService.UploadImage(apiKey, localissueCardPicPath);
            gwsPerson = new GwsPerson();
            gwsPerson.setIDCardNumber(idCardNumber);
            gwsPerson.setIssueCardPicId(issueCardPicId);
            gwsPerson.setLocalIssueCardPicPath(localissueCardPicPath);
            gwsPersonMapper.insertOneRecord(gwsPerson);
        }
        // 表有该人员记录且含有本地图片路径,但没有工务署图片id：直接上传工务署，然后保存
        else if (gwsPerson.getLocalIssueCardPicPath() == null) {
            localissueCardPicPath = gwsPerson.getLocalIssueCardPicPath();
            File file = new File(localissueCardPicPath);
            if (file.exists()) {
                localissueCardPicPath = StoreFileUtil.storePersonHeadImg(yzwProjectCode, issueInlineCardPic);
                if (localissueCardPicPath == null)
                    return "";
                issueCardPicId = innerFormalGWSCWRService.UploadImage(apiKey, localissueCardPicPath);
                gwsPerson = new GwsPerson();
                gwsPerson.setIDCardNumber(idCardNumber);
                gwsPerson.setIssueCardPicId(issueCardPicId);
                gwsPerson.setLocalIssueCardPicPath(localissueCardPicPath);
                gwsPersonMapper.insertOneRecord(gwsPerson);
            } else {
                issueCardPicId = innerFormalGWSCWRService.UploadImage(apiKey, localissueCardPicPath);
                gwsPerson = new GwsPerson();
                gwsPerson.setIDCardNumber(idCardNumber);
                gwsPerson.setIssueCardPicId(issueCardPicId);
                gwsPerson.setLocalIssueCardPicPath(localissueCardPicPath);
                gwsPersonMapper.insertOneRecord(gwsPerson);
            }
        }
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        issueCardPicId = gwsPerson.getIssueCardPicId();

        return issueCardPicId;
    }

    // 图片处理-获取近身照id issueInlineCardPic是在线图片地址 将图片文件存入本地，并且加上jpg后缀，然后再存入数据库中
    public String imgDealWithGetIssueCardPicId(String apiKey, String idCardNumber, String projectGuid,
                                               String issueInlineCardPic) {
        GwsPerson gwsPerson = null;
        String issueCardPicId = null;
        String localissueCardPicPath = null;
        // 查询本地表是否保存有
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        // 表没有该人员记录或者图片路径为空的情况：下载云筑网在线图片然后上传工务署，然后保存
        if (gwsPerson == null || gwsPerson.getLocalIssueCardPicPath() == null
                || gwsPerson.getIssueCardPicId() == null) {
            localissueCardPicPath = StoreFileUtil.storeYfPersonIssueImg(projectGuid, issueInlineCardPic);
            if (localissueCardPicPath == null)
                return "";
            issueCardPicId = innerFormalGWSCWRService.UploadImage(apiKey, localissueCardPicPath);
            gwsPerson = new GwsPerson();
            gwsPerson.setIDCardNumber(idCardNumber);
            gwsPerson.setIssueCardPicId(issueCardPicId);
            gwsPerson.setLocalIssueCardPicPath(localissueCardPicPath);
            gwsPersonMapper.insertOneRecord(gwsPerson);
        }

        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        issueCardPicId = gwsPerson.getIssueCardPicId();

        return issueCardPicId;
    }

    // 图片处理-获取近身照id issueInlineCardPic是在线图片地址 将图片文件存入本地，并且加上jpg后缀，然后再存入数据库中
    public String imgDealWithAndSuffixGetHeadPathId(String apiKey, String idCardNumber, String projectGuid,
                                                    String headInlineImagePath) {
        GwsPerson gwsPerson = null;
        String headImagePathId = null;
        String localHeadImagePath = null;
        // 查询本地表是否保存有
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        // 表没有该人员记录或者图片路径为空的情况：下载云筑网在线图片然后上传工务署，然后保存
        if (gwsPerson == null || gwsPerson.getLocalHeadImagePath() == null || gwsPerson.getHeadImagePathId() == null) {
            localHeadImagePath = StoreFileUtil.storeYfPersonHeadImg(projectGuid, headInlineImagePath);
            if (localHeadImagePath == null)
                return "";
            headImagePathId = innerFormalGWSCWRService.UploadImage(apiKey, localHeadImagePath);
            gwsPerson = new GwsPerson();
            gwsPerson.setIDCardNumber(idCardNumber);
            gwsPerson.setHeadImagePathId(headImagePathId);
            gwsPerson.setLocalHeadImagePath(localHeadImagePath);
            gwsPersonMapper.insertOneRecord(gwsPerson);
        }

        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        headImagePathId = gwsPerson.getHeadImagePathId();

        return headImagePathId;
    }

    // 图片处理-获取头像id headInlineImagePath是在线图片地址
    public String imgDealWithGetHeadPathId(String apiKey, String idCardNumber, Integer yzwProjectCode,
                                           String headInlineImagePath) {
        GwsPerson gwsPerson = null;
        String headImagePathId = null;
        String localHeadImagePath = null;
        // 查询本地表是否保存//先保留】】】】】
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        localHeadImagePath = StoreFileUtil.storePersonHeadImg(yzwProjectCode, headInlineImagePath);
        if (localHeadImagePath == null)
            return "";
        // 表没有该人员记录或者图片路径为空的情况：下载云筑网在线图片然后上传工务署，然后保存 新增记录
        if (gwsPerson == null) {
            storePersonHeadImgAndStroeDb(apiKey, yzwProjectCode, localHeadImagePath, idCardNumber);
        }
        // 表有该人员记录不含有本地图片路径记录 更新记录-上传并新增记录 / 更新表中的路径为新路径***.jpeg 更新记录
        else if (gwsPerson.getHeadImagePathId() == null
                || !gwsPerson.getLocalHeadImagePath().equals(localHeadImagePath)) {
            storePersonHeadImgAndUpadteDb(apiKey, yzwProjectCode, localHeadImagePath, idCardNumber);
        }
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        headImagePathId = gwsPerson.getHeadImagePathId();

        return headImagePathId;
    }

    /**
     * 处理宇泛图片
     *
     * @param apiKey
     * @param idCardNumber
     * @param yzwProjectCode
     * @param headInlineImagePath
     * @return
     */
    public String imgDealWithGetHeadPathId(String apiKey, String idCardNumber, String projectGuid,
                                           String headInlineImagePath) {
        GwsPerson gwsPerson = null;
        String headImagePathId = null;
        String localHeadImagePath = null;
        // 查询本地表是否保存//先保留】】】】】
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        localHeadImagePath = StoreFileUtil.storeYfPersonHeadImg(projectGuid, headInlineImagePath);
        if (localHeadImagePath == null)
            return "";
        // 表没有该人员记录或者图片路径为空的情况：下载云筑网在线图片然后上传工务署，然后保存 新增记录
        if (gwsPerson == null) {
            storePersonHeadImgAndStroeDb(apiKey, localHeadImagePath, idCardNumber);
        }
        // 表有该人员记录不含有本地图片路径记录 更新记录-上传并新增记录 / 更新表中的路径为新路径***.jpeg 更新记录
        else if (gwsPerson.getHeadImagePathId() == null
                || !gwsPerson.getLocalHeadImagePath().equals(localHeadImagePath)) {
            storePersonHeadImgAndUpadteDb(apiKey, localHeadImagePath, idCardNumber);
        }
        gwsPerson = gwsPersonMapper.selectOneRecordByIDCardNumber(idCardNumber);
        headImagePathId = gwsPerson.getHeadImagePathId();

        return headImagePathId;
    }

    // 单例测试上传
    // public void singleTest() {
    // try {
    // String image_id = innerFormalGWSCWRService.UploadImage(
    // "D:\\uploadGwsStoreYzwImg\\yzwprojectattendancelistnew\\00b2a-c63b-410f-bae4-ac662bdf7fa9.jpg");
    // log.info("image_id:" + image_id);
    // } catch (Exception e) {
    // // TODO: handle exception
    // }
    //
    // }

    // 获得工种
    public void getDictListJobName() throws ParseException, NoSuchAlgorithmException {
        List<GwsDictListJobName> l = innerFormalGWSCWRService.getDictListJobName();
        log.info("List<GwsDictListJobName>:" + l);
        for (GwsDictListJobName gwsDictListJobName : l) {
            gwsCWRMapper.innerOneDictListJobNameRecord(gwsDictListJobName);
        }
    }

    // 获得团队/班组类型
    public void getTeamType() throws ParseException, NoSuchAlgorithmException {
        List<GwsTeamType> l = innerFormalGWSCWRService.GetTeamType();
        log.info("List<GwsTeamType>:" + l);
        for (GwsTeamType gwsTeamType : l) {
            gwsCWRMapper.innerOneTeamTypeRecord(gwsTeamType);
        }
    }

    private List<YzwWorkerList> getPerData(Integer yzwProjectCode) {
        log.info("工务署业务模块-上传人员到工务署-开始获取本机要上传的项目人员..");
        List<YzwWorkerList> yl = yzwWorkerListMapper.findMultipleRecordByProjectSysNo(yzwProjectCode, true);
        // List<YzwWorkerList> yl =
        // gwsCWRMapper.selectPresenceOfWorkerList(yzwProjectCode,
        // "iDCardNumber");
        if (yl != null) {
            log.info("工务署业务模块-上传人员到工务署-获取本机要上传的项目人员完成，获取到" + yl.size() + "条人员记录");
            return yl;
        } else {
            log.info("工务署业务模块-上传人员到工务署-获取本机要上传的项目人员完成,数据为空，即将结束该次会话");
            return null;
        }
    }

    // 验证授权是否上报 , 返回云筑网号
    private Integer verifyTheAuthorization(Integer yzwProjectCode, String projectName) {

        if (yzwProjectCode == null || yzwProjectCode == 0) {
            IntelligentsiteCorrespondsItemtable intelligentsiteCorrespondsItemtable = intelligentsiteCorrespondsMapper
                    .selectOneRecordByProjectName(projectName);
            yzwProjectCode = intelligentsiteCorrespondsItemtable.getIntelligentsite_attendance_id();
        }

        if (yzwProjectCode == null) {
            log.error("工务署业务模块-上传人员到工务署-项目对应主体数据验证不通过.原因：平台表不存在standardProjectName字段或Intelligentsite_attendance_id为空："
                    + projectName);
            return null;
        }
        log.info("工务署业务模块-上传人员到工务署-项目对应主体数据验证完成.");
        return yzwProjectCode;
    }

    /**
     * 传入本地头像地址-返回上传工务署后的头像图片id头像照 包含表更新记录操作
     *
     * @param yzwProjectCode     云筑网项目号
     * @param localHeadImagePath 头像本地地址
     * @return
     */
    public String storePersonHeadImgAndUpadteDb(String apiKey, Integer yzwProjectCode, String localHeadImagePath,
                                                String idCardNumber) {
        String headImagePathId = innerFormalGWSCWRService.UploadImage(apiKey, localHeadImagePath);
        GwsPerson gwsPerson = new GwsPerson();
        gwsPerson.setIDCardNumber(idCardNumber);
        gwsPerson.setHeadImagePathId(headImagePathId);
        gwsPerson.setLocalHeadImagePath(localHeadImagePath);
        Integer upCount = gwsPersonMapper.updateOneRecord(gwsPerson);
        log.info(idCardNumber + "的头像地址更新了" + upCount + "条数据");
        return headImagePathId;
    }

    public String storePersonHeadImgAndUpadteDb(String apiKey, String localHeadImagePath, String idCardNumber) {
        String headImagePathId = innerFormalGWSCWRService.UploadImage(apiKey, localHeadImagePath);
        GwsPerson gwsPerson = new GwsPerson();
        gwsPerson.setIDCardNumber(idCardNumber);
        gwsPerson.setHeadImagePathId(headImagePathId);
        gwsPerson.setLocalHeadImagePath(localHeadImagePath);
        Integer upCount = gwsPersonMapper.updateOneRecord(gwsPerson);
        log.info(idCardNumber + "的头像地址更新了" + upCount + "条数据");
        return headImagePathId;
    }

    /**
     * 传入本地头像地址-返回上传工务署后的头像图片id头像照 包含表新增记录操作
     *
     * @param yzwProjectCode     云筑网项目号
     * @param localHeadImagePath 头像本地地址
     * @return
     */
    public String storePersonHeadImgAndStroeDb(String apiKey, Integer yzwProjectCode, String localHeadImagePath,
                                               String idCardNumber) {
        String headImagePathId = innerFormalGWSCWRService.UploadImage(apiKey, localHeadImagePath);
        GwsPerson gwsPerson = new GwsPerson();
        gwsPerson.setIDCardNumber(idCardNumber);
        gwsPerson.setHeadImagePathId(headImagePathId);
        gwsPerson.setLocalHeadImagePath(localHeadImagePath);
        gwsPersonMapper.insertOneRecord(gwsPerson);
        return headImagePathId;
    }

    public String storePersonHeadImgAndStroeDb(String apiKey, String localHeadImagePath, String idCardNumber) {
        String headImagePathId = innerFormalGWSCWRService.UploadImage(apiKey, localHeadImagePath);
        GwsPerson gwsPerson = new GwsPerson();
        gwsPerson.setIDCardNumber(idCardNumber);
        gwsPerson.setHeadImagePathId(headImagePathId);
        gwsPerson.setLocalHeadImagePath(localHeadImagePath);
        gwsPersonMapper.insertOneRecord(gwsPerson);
        return headImagePathId;
    }

}
